package com.epam.command.user;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.epam.command.logic.Command;
import com.epam.dao.impl.TouristVoucherDAO;
import com.epam.entity.TouristVoucher;
import com.epam.util.ConfigurationManager;

public class AddToCartCommand implements Command {
	
	

	@SuppressWarnings("unchecked")
	@Override
	public String execute(HttpServletRequest request,
			HttpServletResponse response) {
		
		List<TouristVoucher> cart;
		int voucherId = Integer.parseInt(request.getParameter("voucher"));
		TouristVoucherDAO tvd = new TouristVoucherDAO();
		TouristVoucher tv = tvd.findByID(voucherId);
		String page = ConfigurationManager.getConfig(ConfigurationManager.OPERATION_SUCCESSFUL);
		HttpSession session = request.getSession();
		
		if (session.getAttribute("cart") == null) {
			cart = new ArrayList<TouristVoucher>();
		} else {
			cart = (List<TouristVoucher>) session.getAttribute("cart");
		}
		
		for (TouristVoucher t : cart) {
			if (t.getId()==voucherId) {
				request.setAttribute("message", "Tour already in cart");
				return page;
			}
		}
		
		cart.add(tv);
		session.setAttribute("cart", cart);
		
		return page;
		
	}

}
